package gestionedt.controllers;

import gestionedt.controllers.exceptions.NonexistentEntityException;
import gestionedt.models.Creneau;
import gestionedt.models.Pool;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import org.eclipse.persistence.config.HintValues;
import org.eclipse.persistence.config.QueryHints;

/**
 *
 *
 */
public class PoolJpaController {

    public PoolJpaController() {
        emf = Persistence.createEntityManagerFactory("GestionEDTPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Pool pool) {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            em.persist(pool);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Pool pool) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            pool = em.merge(pool);
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = pool.getId();
                if (findPool(id) == null) {
                    throw new NonexistentEntityException("The pool with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Pool pool;
            try {
                pool = em.getReference(Pool.class, id);
                pool.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The pool with id " + id + " no longer exists.", enfe);
            }
            em.remove(pool);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Pool> findPoolEntities() {
        return findPoolEntities(true, -1, -1);
    }

    public List<Pool> findPoolEntities(int maxResults, int firstResult) {
        return findPoolEntities(false, maxResults, firstResult);
    }

    private List<Pool> findPoolEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Pool as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Pool findPool(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Pool.class, id);
        } finally {
            em.close();
        }
    }

    public int getPoolCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Pool as o").getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

    public List<Pool> findPoolsByIds(int[] ids) {

        if(ids.length == 0)
            return new ArrayList<Pool>(0);

        EntityManager em = getEntityManager();
        try {
            String strQ = "SELECT p " +
                          "FROM Pool AS p " +
                          "WHERE p.id IN (?1";
            for(int i = 2; i <= ids.length; i++)
                strQ += (", ?"+i);
            strQ += ")";
            Query q = em.createQuery(strQ);
            for(int i = 1; i <= ids.length; i++)
                q.setParameter(i, ids[i-1]);

            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public List<Pool> getList() {
        EntityManager em = getEntityManager();
        try {
            String strQ = "SELECT p " +
                          "FROM Pool AS p " +
                          "ORDER BY p.libelle";
            return em.createQuery(strQ).getResultList();
        } finally {
            em.close();
        }
    }

    /**
     * Récupère une liste de pools avec leurs relations préchargées.
     * @param idPool paramètre facultatif, s'il vaut null tous les pools seront récupérés
     * @return
     */
    private List<Pool> findAvecRel(Integer idPool) {
        EntityManager em = getEntityManager();
        try {
            String strQ = "SELECT DISTINCT p " +
                          "FROM Pool AS p " +
                            "LEFT JOIN FETCH p.moduleCollection ";
            if(idPool != null)
                strQ += "WHERE p.id = :idPool ";
            strQ += "ORDER BY p.libelle";

            Query q = em.createQuery(strQ);
            q.setHint(QueryHints.REFRESH, HintValues.TRUE);
            if(idPool != null)
                q.setParameter("idPool", idPool);

            return q.getResultList();
        } finally {
            em.close();
        }
    }

    /**
     * Récupère une liste de pools avec leurs relations préchargées.
     * @return
     */
    public List<Pool> findPoolsAvecRel() {
        return this.findAvecRel(null);
    }

    /**
     * Recupère un pool avec ses relations préchargées.
     * @param idEnseignant
     * @return
     */
    public Pool findPoolAvecRel(Integer idPool) {
        List<Pool> liste = findAvecRel(idPool);
        return (liste.size() > 0 ? liste.get(0) : null);
    }

    /**
     * Retourne le nombre restant de prestations autorisées pour un créneau donné
     * dans chaque pool passé en paramètre.
     * @param creneau
     * @param pools liste des pools concernés
     * @return table de hachage qui retournera le nombre de prestations
     * restant en fonction du pool donné
     */
    public Map<Pool, Integer> getNbPrestRestant(Creneau creneau, List<Pool> pools) {

        if(pools.size() == 0)
            return new HashMap<Pool, Integer>(0);

        Map<Pool, Integer> nbRestant = new HashMap<Pool, Integer>(pools.size());
        EntityManager em = getEntityManager();
        try {
            String strQ = "SELECT NEW gestionedt.controllers.NbPrestRestant(pool, COUNT(DISTINCT prest)) " +
                          "FROM Pool AS pool " +
                            "LEFT JOIN pool.moduleCollection m " +
                              "LEFT JOIN m.prestationCollection prest " +
                          "WHERE prest.numCreneau = :creneau ";
            strQ += "AND pool.id IN (?1";
           for(int i = 2; i <= pools.size(); i++)
                strQ += (", ?"+i);
            strQ += ") ";
            strQ += "GROUP BY pool ";

            Query q = em.createQuery(strQ);
            q.setParameter("creneau", creneau);
            for(int i = 1; i <= pools.size(); i++)
                q.setParameter(i, pools.get(i-1).getId());

            List<NbPrestRestant> liste = q.getResultList();
            for(NbPrestRestant nb : liste)
                nbRestant.put(nb.getPool(), nb.getNbPrestRestant());

            return nbRestant;

        } finally {
            em.close();
        }
    }

}

/**
 * Classe utilitaire utilisée pour récupérer un résultat de requête JPQL.
 */
class NbPrestRestant {

    private Pool pool;
    private int nbPrestRestant;

    public NbPrestRestant(Pool pool, Long nbPrestTotal) {
        this.pool = pool;
        this.nbPrestRestant = pool.getNbPrestMaxParPlage() - nbPrestTotal.intValue();
    }

    public int getNbPrestRestant() {
        return nbPrestRestant;
    }

    public Pool getPool() {
        return pool;
    }

}
